import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import { saveAs } from 'file-saver'

// PDF导出（网页1导出逻辑优化）
export const exportPdf = (element, fileName = 'document') => {
  html2canvas(element, {
    scale: 2,
    useCORS: true,
    allowTaint: true
  }).then(canvas => {
    const imgData = canvas.toDataURL('image/png', 1.0)
    const pdf = new jsPDF('p', 'mm', 'a4')
    const imgWidth = 190
    const imgHeight = (canvas.height * imgWidth) / canvas.width

    pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight)
    pdf.save(`${fileName}.pdf`)
  })
}

// Word导出（网页3模板生成思路）
// 修改后的exportUtil.js
export const exportWord = async (data, templateFile) => {
  try {
    const response = await fetch(`/templates/${templateFile}`);
    const buffer = await response.arrayBuffer();

    // 增加ZIP头校验
    if (!isValidZipHeader(buffer)) {
      throw new Error("Invalid ZIP file structure");
    }

    const zip = new PizZip(buffer);
    const doc = new Docxtemplater().loadZip(zip);

    // 增加异步操作等待
    await doc.resolveData({
      ...data,
      img: async (tagValue) => {
        const response = await fetch(tagValue);
        return response.arrayBuffer();
      }
    });

    const blob = doc.getZip().generate({ type: "blob" });
    saveAs(blob, `Resume_${Date.now()}.docx`);
  } catch (error) {
    console.error("Export Error:", error);
    throw new Error(`导出失败: ${error.message}`);
  }
}

function isValidZipHeader(buffer) {
  // 检查ZIP文件头签名
  const header = new Uint8Array(buffer.slice(0,4));
  return header[0] === 0x50 && header[1] === 0x4B &&
         header[2] === 0x03 && header[3] === 0x04;
}
